package bsts.view.subscription;

// updated

import bsts.model.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import bsts.model.Account;
import bsts.model.CableTV;
import bsts.model.Feature;
import bsts.model.Plan;
import bsts.model.Subscription;
import bsts.model.User;

import java.awt.FlowLayout;
import java.awt.GridLayout; //import java.awt.ItemSelectable;
import javax.swing.*;

import bsts.application.BSTSApplication;
import bsts.controller.*;

import bsts.util.validation.TelephoneValidation;

public class NewSubscriptionWindow extends JFrame {

	private static final long serialVersionUID = 1L;
	private BSTSApplication manager;
	private JFrame container;
	private JFrame me;

	private Account currentSelectedAccount;
	private Customer customer;

	private JPanel pnlN;
	private JPanel pnlButtons;
	private JComboBox planCombo;
	private JLabel lblPlan;
	private JLabel lblPhoneNo;
	private JLabel lblDescription;
	private JTextArea txtDescription;
	private JTextField phoneNoTxt;
	private JButton btnSave;
	private JButton btnCancel;
	private SubscriptionController subscriptionController;
	private AddFeaturePanel addFeaturePanel;

	private ArrayList<Plan> availablePlans = new ArrayList<Plan>();
	private ArrayList<Feature> features = new ArrayList<Feature>();
	
	private TelephoneValidation tv = new TelephoneValidation();

	private WindowListener windowListener = new WindowAdapter() {
		public void windowClosing(WindowEvent e) {
			manager.getViewManager().goBackParent(container, me);
		}
	};

	public NewSubscriptionWindow(BSTSApplication manager, JFrame container,
			Account account, Customer customer) {
		super("BSTS - New Subscription");
		this.manager = manager;
		this.container = container;
		this.me = this;
		this.currentSelectedAccount = account;
		this.customer = customer;
		this.addWindowListener(windowListener);
		init();
	}

	private void init() {
		subscriptionController = new SubscriptionController();
		availablePlans = subscriptionController.getDefaultPlans();

		pnlN = new JPanel(new GridLayout(3, 2));
		pnlButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));

		this.getContentPane().setLayout(
				new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));

		lblPlan = new JLabel("Plan:");
		lblPhoneNo = new JLabel("Phone no:");
		lblDescription = new JLabel("Description:");
		phoneNoTxt = new JTextField();
		txtDescription = new JTextArea();
		txtDescription.setEditable(false);
		planCombo = new JComboBox();
		btnSave = new JButton("Save");
		btnCancel = new JButton("Cancel");

		for (Plan plan : availablePlans) {
			planCombo.addItem(plan.getName());
		}

		if (availablePlans.size() > 0) {
			features = availablePlans.get(0).getFeaturesClone();
			txtDescription.setText(availablePlans.get(0).getDescription());
		}

		addFeaturePanel = new AddFeaturePanel(features);

		pnlN.add(lblPlan);
		pnlN.add(planCombo);
		pnlN.add(lblDescription);
		pnlN.add(txtDescription);
		pnlN.add(lblPhoneNo);
		pnlN.add(phoneNoTxt);

		pnlButtons.add(btnSave);
		pnlButtons.add(btnCancel);

		this.getContentPane().add(pnlN);
		this.getContentPane().add(addFeaturePanel);
		this.getContentPane().add(pnlButtons);

		ActionListener actionListener = new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				/*
				 * System.out .println("Command: " +
				 * actionEvent.getActionCommand()); ItemSelectable is =
				 * (ItemSelectable) actionEvent.getSource();
				 * System.out.println(", Selected: " + selectedString(is));
				 */
				populateFeatures();
				populateValues();
			}
		};

		ActionListener actionListenerSave = new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				// System.out.println("Subscription saved successfully");
				handleSubscriptionCreation();
			}
		};

		ActionListener actionListenerCancel = new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				manager.getViewManager().goBackParent(container, me);
			}
		};

		planCombo.addActionListener(actionListener);
		btnSave.addActionListener(actionListenerSave);
		btnCancel.addActionListener(actionListenerCancel);
		
		phoneNoTxt.setInputVerifier(tv);
		phoneNoTxt.addActionListener(tv);
	}

	/*
	 * private static String selectedString(ItemSelectable is) { Object
	 * selected[] = is.getSelectedObjects(); return ((selected.length == 0) ?
	 * "null" : (String) selected[0]); }
	 */

	private void populateValues() {
		int selectedIndex = planCombo.getSelectedIndex();
		Plan selectedPlan = availablePlans.get(selectedIndex);

		txtDescription.setText(selectedPlan.getDescription());

		if (selectedPlan instanceof CableTV) {
			lblPhoneNo.setVisible(false);
			phoneNoTxt.setVisible(false);
		} else {
			lblPhoneNo.setVisible(true);
			phoneNoTxt.setVisible(true);
		}

		this.getContentPane().repaint();
	}

	private void populateFeatures() {
		int selectedIndex = planCombo.getSelectedIndex();
		Plan selectedPlan = availablePlans.get(selectedIndex);

		features = selectedPlan.getFeaturesClone();
		for (Feature feature : features)
			System.out.println(feature.getName());

		addFeaturePanel = new AddFeaturePanel(features);

		this.getContentPane().remove(1);
		this.getContentPane().add(addFeaturePanel, 1);
		this.getContentPane().repaint();
	}

	private void handleSubscriptionCreation() {
		int selectedIndex = planCombo.getSelectedIndex();

		Plan selectedPlan = availablePlans.get(selectedIndex).clone();
		if ((selectedPlan instanceof DigitalVoice)
				|| (selectedPlan instanceof MobileVoice)) {
			if (phoneNoTxt.getText().trim().length() <= 0) {
				JOptionPane.showMessageDialog(me, "Please enter phone no.");
				return;
			}
		}

		if (selectedPlan instanceof DigitalVoice) {
			((DigitalVoice) selectedPlan).setPhoneNo(phoneNoTxt.getText()
					.trim());
		} else if (selectedPlan instanceof MobileVoice) {
			((MobileVoice) selectedPlan)
					.setPhoneNo(phoneNoTxt.getText().trim());
		}

		System.out.println(selectedPlan.getName());
		Subscription subscription;
		User currentLoginUser = manager.getLoginUser();
		ArrayList<Feature> selectedFeatures = addFeaturePanel
				.getSelectedFeatures();

		for (Feature feature : selectedFeatures)
			feature.setSubscriptionStatus(SubscriptionStatus.Activated);

		selectedPlan.setFeatures(selectedFeatures);

		subscription = subscriptionController.createSubstription(
				this.currentSelectedAccount, Calendar.getInstance().getTime(),
				null, selectedPlan, currentLoginUser);
		System.out.println("Subscritption ID is "
				+ subscription.getSubscriptionId());
		JOptionPane.showMessageDialog(null,
				"Subscription created successfully. SubscriptionID: "
						+ subscription.getSubscriptionId());

		System.out.println("after saved: " + subscription.getPlan().getName());
		currentSelectedAccount.addSubscription(subscription);
		customer.putAccount(currentSelectedAccount);

		manager.getCustomerManager().updateCustomer(customer);

		manager.getViewManager().goBackParent(container, me);
	}

}
